#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>


struct sockaddr_in server_addr;

#define handlle_error(cmd,result){  \
    if (result < 0)                 \
    {                               \
        perror(cmd);                \
        return -1;                  \
    }                               \
}   

void * write_thread(void * arg){
    // 将客户端发送的消息读取打印到控制台
    
    int fd = *(int *)arg;
    char *buf;
    ssize_t count ;
    count = sizeof(server_addr);
    buf = malloc(10224);
    while (fgets(buf,1024,stdin))
    {
        printf("发送消息到服务端\n");
        sendto(fd,buf,1024,0,(struct sockaddr *)&server_addr,count);
        if (recvfrom(fd,buf,1024,0,(struct sockaddr *)&server_addr,&count)>0)
        {
            printf("收到服务端的返回值%s",buf);
        }
        
    }
    free(buf);
}


int main(int argc, char const *argv[])
{
    
    int sock_fd,tmp_result,pid;
    pthread_t write_thread_t;
    memset(&server_addr,0,sizeof(server_addr));
    

    // 1.赋值
    server_addr.sin_family = AF_INET;
    inet_pton(AF_INET,"192.168.10.150",&server_addr.sin_addr);
    server_addr.sin_port = htons(7777);

    // 2.创建socker
    sock_fd = socket(AF_INET,SOCK_DGRAM,0);
    handlle_error("socket",sock_fd);
    
    // 创建写线程
    pthread_create(&write_thread_t,NULL,write_thread,&sock_fd);

    // 挂起等待子线程运行完成
    pthread_join(write_thread_t,NULL);
    
    close(sock_fd);

    return 0;
}
